<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20" class="my-3">
        <el-col :span="4">
          <button
            @click="delAllSelection"
            type="button"
            class="el-button handle-del el-button--primary"
          >
            <i class="el-icon-delete"></i>
            <span>批量删除</span>
          </button>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" v-model="searchContent" clearable>
              <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="centerDialogVisible = true">
              <i class="el-icon-plus"></i>
              <span>添加角色</span>
            </el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 角色列表区 -->

      <el-table
        border
        stripe
        :data="roles"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column type="selection" show-overflow-tooltip></el-table-column>
        <el-table-column
          type="index"
          :index="indexSort"
          sortable
          align="center"
          label="#"
          width="50"
        ></el-table-column>
        <el-table-column align="center" prop="name" label="角色名称"></el-table-column>

        <el-table-column align="center" width="180px" label="操作">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showMessage(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteid(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- 留言分页pc -->
      <div class="row">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            background
            :page-sizes="[4, 6, 8]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色角色"
      :visible.sync="centerDialogVisible"
      width="50%"
      center
      @close="addDialogClose"
    >
      <!-- 表单内容区域  -->
      <el-form
        :model="addForm"
        status-icon
        :rules="addFromRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input type="text" clearable v-model="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
        <el-button @click="addresetForm">重置</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色角色 -->
    <el-dialog title="修改角色角色" :visible.sync="centerDialogVisible2" width="50%" center>
      <el-form
        :model="editForm"
        status-icon
        :rules="addFromRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input type="text" clearable v-model="editForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'qs'
export default {
  data() {
    var validImgSrc = (rule, value, callback) => {
      var patt1 = /(http|https):\/\/([\w.]+\/?)\S*/
      if (!value.match(patt1)) {
        callback(new Error('请按格式填写'))
      } else {
        callback()
      }
    }
    return {
      // 分页
      total: 0,
      pageSize: 6,
      currentPage: 1,
      searchContent: '', // 搜索内容
      roles: [],
      colorArr: ['red', 'blue', 'green', 'black'],
      // 弹出框
      centerDialogVisible: false,
      centerDialogVisible2: false,
      dialogVisible: false,
      //添加
      addForm: {
        name: '',
      },
      //修改
      editForm: {
        id: 6,

        name: '',
      },
      //验证规则
      addFromRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      //删除列表

      multipleSelection: [], //批量删除列表
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    // 获取所有角色
    async getRoles() {
      const { data } = await this.$http.get(
        '/nanny/type/list?' +
          qs.stringify({
            current: this.currentPage,
            size: this.pageSize,
          })
      )
      if (data.code == 200) {
        this.roles = data.data.records
        this.total = data.data.total
      }

      console.log(data)
    },
    // 分页
    handleSizeChange(pageSize) {
      this.currentPage = 1
      this.pageSize = pageSize
      this.getRoles()
    },
    // 跳转页数
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getRoles()
    },
    // 添加角色信息
    async add() {
      this.$refs.addFormRef.validate(async (valid, obj) => {
        if (valid) {
          const { data } = await this.$http.post('/nanny/type/save', {
            name: this.addForm.name,
            // code: this.addForm.code,
            // priority: this.addForm.priority,
            // remark: this.addForm.remark,
          })
          if (data.code == 200) {
            this.addresetForm()
            this.$message.success('添加成功！')
            this.getRoles()
          } else if (data.code == 400) {
            this.$message.error(data.message)
          } else {
            this.$message.error('添加失败!')
          }
        } else {
          this.$message.error('表单填写有误，请检查后提交！')
        }
        this.centerDialogVisible = false
      })
    },
    // 查询角色信息
    async search() {
      const { data } = await this.$http.get(
        '/nanny/type/list?' +
          qs.stringify({
            name: this.searchContent,
            current: this.currentPage,
            size: this.pageSize,
          })
      )
      if (data.code == 200) {
        this.roles = data.data.records
        this.total = data.data.total
        this.searchContent = ''
      } else {
        this.$message.error('查询角色不存在')
      }
    },
    // 修改角色信息前获取点击角色的信息
    showMessage(row) {
      this.editForm.id = row.id
      this.editForm.name = row.name

      this.centerDialogVisible2 = true
    },
    // 修改角色信息
    async edit() {
      this.$refs.editFormRef.validate(async (valid, obj) => {
        if (valid) {
          const { data } = await this.$http.post('/nanny/type/update', {
            id: this.editForm.id,
            name: this.editForm.name,
          })
          if (data.code == 200) {
            this.$message.success('修改成功！')

            this.getRoles()
          } else if (data.code == 400) {
            this.$message.error(data.message)
          } else {
            this.$message.error('修改失败！')
          }
        } else {
          this.$message.error('表单填写有误，请检查后提交！')
        }
        this.centerDialogVisible2 = false
      })
    },

    //添加 关闭添加界面 清空所填信息
    addresetForm() {
      this.$refs.addFormRef.resetFields()
    }, //添加 取添加改信息 清空所填信息
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 删出角色信息
    async deleteid(row) {
      const confirmresult = await this.$confirm(
        '此操作将永久删除该该角色,不可恢复， 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmresult != 'confirm') {
        return this.$message.info('已取消删除！！')
      } else {
        let did = []
        did.push(row.id)
        const { data } = await this.$http.post('/nanny/type/delete', did)
        if (data.code == 200) {
          this.$message.success('成功删除了 ' + row.name + '的角色')
          this.getRoles()
        } else if (data.code == 400) {
          this.$message.error(data.message)
        } else {
          this.$message.error('删除失败')
        }
        this.centerDialogVisible2 = false
      }
    },
    // 监听哪些行数改变
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除按钮
    async delAllSelection() {
      const length = this.multipleSelection.length
      let delList = []
      for (let i = 0; i < length; i++) {
        delList.push(this.multipleSelection[i].id)
      }
      const { data } = await this.$http.post('/nanny/type/delete', delList)
      if (data.code == 200) {
        let str = ''
        for (let i = 0; i < length; i++) {
          str += this.multipleSelection[i].name + ' '
        }
        this.$message.error(`成功删除了${str}` + '的角色')
        this.getRoles()
      } else if (data.code == 400) {
        this.$message.error(data.message)
      } else {
        this.$message.error('删除失败')
      }
      this.multipleSelection = [] // 删除后清空列表
    },
    // 排序
    indexSort(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1
    },
  },
}
</script>

<style lang="less" scoped>
.table-td-headPortrait {
  width: 40px;
  height: 40px;
}
</style>